package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO insertSubmit(OrdersSubmitDTO ordersSubmitDTO) {
        //处理异常
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartMapper.selectCart(shoppingCart);
        if (list == null || list.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向订单表添加一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setEstimatedDeliveryTime(LocalDateTime.now().plusHours(1));
        orders.setPayStatus(Orders.UN_PAID);
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());

        orderMapper.insertSubmit(orders);
        //向订单明细表添加n条数据

        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailMapper.insertSubmit(orderDetail);
        }


        //订单成功生成清空当前用户购物车数据
        shoppingCartMapper.deleteCart(shoppingCart);
        //封装Vo返回结果
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderTime(orders.getOrderTime());

        return orderSubmitVO;
    }

    /**
     * 用户端历史订单查询
     *
     * @param
     * @return
     */
    @Override
    @Transactional
    public PageResult historyOrders(Integer page, Integer pageSize, Integer status) {
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        PageHelper.startPage(page, pageSize);

        Page<Orders> orders = orderMapper.historyOrders(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList<>();

        for (Orders order : orders) {
            Long id = order.getId();
            List<OrderDetail> orderDetails = orderDetailMapper.getById(id);
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            orderVO.setOrderDetailList(orderDetails);
            list.add(orderVO);
        }

        return new PageResult(orders.getTotal(), list);
    }

    /**
     * 用户端取消订单
     *
     * @param id
     */
    @Override
    public void cancel(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.cancel(orders);

    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public OrderVO orderDetail(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .userId(BaseContext.getCurrentId())
                .build();
        Orders orders1 = orderMapper.orderDetail(orders);
        List<OrderDetail> list = orderDetailMapper.getById(orders1.getId());

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders1, orderVO);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setUserId(BaseContext.getCurrentId());
        Orders orders1 = orderMapper.orderDetail(orders);
        orders1.setNumber(String.valueOf(System.currentTimeMillis()));
        orders1.setStatus(Orders.PENDING_PAYMENT);
        orders1.setOrderTime(LocalDateTime.now());
        orders1.setEstimatedDeliveryTime(LocalDateTime.now().plusHours(1));
        orderMapper.insertSubmit(orders1);

        List<OrderDetail> orderDetails = orderDetailMapper.getById(id);
        for (OrderDetail orderDetail : orderDetails) {
            orderDetail.setOrderId(orders1.getId());
            orderDetailMapper.insertSubmit(orderDetail);
        }

    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> orders = orderMapper.conditionSearch(ordersPageQueryDTO);
        List<OrderVO> orderVOS = new ArrayList<>();
        for (Orders order : orders) {
            OrderVO orderVO = new OrderVO();
            String orderDishes = "";
            Long orderId = order.getId();
            List<OrderDetail> orderDetails = orderDetailMapper.getById(orderId);
            for (OrderDetail orderDetail : orderDetails) {
                String name = orderDetail.getName();
                String number = String.valueOf(orderDetail.getNumber());
                String s = name + "*" + number + ";";
                orderDishes = orderDishes + s;
            }
            BeanUtils.copyProperties(order, orderVO);
            orderVO.setOrderDishes(orderDishes);
            orderVOS.add(orderVO);
        }
        return new PageResult(orders.getTotal(), orderVOS);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {

        Integer toBeConfirmed = orderMapper.statistics(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.statistics(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.statistics(Orders.DELIVERY_IN_PROGRESS);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        return orderStatisticsVO;
    }

    @Override
    public OrderVO detailsGet(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        Orders orders1 = orderMapper.orderDetail(orders);

        List<OrderDetail> orderDetails = orderDetailMapper.getById(orders1.getId());
        String orderDishes = "";
        for (OrderDetail orderDetail : orderDetails) {
            String name = orderDetail.getName();
            String number = String.valueOf(orderDetail.getNumber());
            String s = name + "*" + number + ";";
            orderDishes = orderDishes + s;
        }
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders1, orderVO);
        orderVO.setOrderDishes(orderDishes);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersConfirmDTO, orders);
        orders.setEstimatedDeliveryTime(LocalDateTime.now().plusHours(1));
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.cancel(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setEstimatedDeliveryTime(LocalDateTime.now().plusHours(1));
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.cancel(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.cancel(orders);
    }

    /**
     * 管理端取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancelAdmin(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO, orders);
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);
        orderMapper.cancel(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        orders.setId(ordersRejectionDTO.getId());
        orders.setCancelReason(ordersRejectionDTO.getRejectionReason());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.cancel(orders);
    }


}
